﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Linq;
using System.Xml;

namespace ontheroad
{
    public partial class imgresultpage : PhoneApplicationPage
    {
        private string id;
        private string title;
        private string type;

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            waitScr.Visibility = Visibility.Visible;
            id = NavigationContext.QueryString["id"];
            title = NavigationContext.QueryString["title"];
            type = NavigationContext.QueryString["type"];
            if (type == "1")
            {
                typetitletxt.Text = "CCTV";
                titletxt.Text = title;
                getImageFromCctv();
            }
            else
            {
                typetitletxt.Text = "INTELLIGENT TRAFFIC SIGNS";
                titletxt.Text = title;
                getImageFromVms();
            }
        }

        //http://athena.traffy.in.th/apis/apitraffy.php?api=getvmsimg&key=3F908B5AE04292BBA07FACCFFAEF3B5AD0B3A07A962CFF3C3A8447E1A8DA7969&appid=00001627&id=1&h=200&w=320

       

        public imgresultpage()
        {
            InitializeComponent();
        }

        private void getImageFromVms()
        {
            
            try
            {
                imgresultlistbox.Items.Clear();
                string uri = "http://athena.traffy.in.th/apis/apitraffy.php?api=getvmsimg&key="
                    + App.traf.sessionkey + "&appid=" + App.traf.appid + "&id=" + id + "&h=200&w=320";
                
                BitmapImage bmp = new BitmapImage(new Uri(uri));
                //imgresult.Source = bmp;
                Image img = new Image();
                img.Source = bmp;
                imgresultlistbox.Items.Add(img);
            }
            catch (Exception)
            {
                MessageBox.Show("Server connection failed, Please wait a minute and try again.");
                NavigationService.GoBack();
                return;
            }
            waitScr.Visibility = Visibility.Collapsed;
            
        }

        private void getImageFromCctv()
        {
            
            try
            {
                List<Image> imgList = new List<Image>();
                for (int i = 0; i < 5; i++)
                {
                    string uri = "http://api.traffy.in.th/apis/apitraffy.php?api=getcctvimg&id="
                    + id + "&num=" + i + "&appid=" + App.traf.appid + "&key=" + App.traf.sessionkey;
                    BitmapImage bmp = new BitmapImage(new Uri(uri));
                    
                    Image img = new Image();
                    img.Source = bmp;
                    imgList.Add(img);
                }
                imgresultlistbox.ItemsSource = imgList;
                
            }
            catch (Exception)
            {
                MessageBox.Show("Server connection failed, Please wait a minute and try again.");
                NavigationService.GoBack();
                return;
            }
            waitScr.Visibility = Visibility.Collapsed;
            
        }

        private void addtofavbut_Click(object sender, System.EventArgs e)
        {
        	// TODO: Add event handler implementation here.
			MessageBoxResult m = MessageBox.Show("add to favorites","Confirm ?",MessageBoxButton.OKCancel);
            if (m == MessageBoxResult.OK)
            {
                string fileName;
                if (type == "1")
                    fileName = "cctvtest10.xaml";
                else
                    fileName = "intsigntest.xaml";
                XElement elm;
                try
                {
                    IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        string readString = reader.ReadToEnd();
                        if (readString.Contains("<id>" + id + "</id>"))
                        {
                            MessageBox.Show("Already exists.");
                            return;
                        }
                        elm = XElement.Parse(readString);
                    }


                    List<int> idList = new List<int>();
                    while (elm.FirstNode as XElement != null)
                    {
                        int idAdd = Convert.ToInt32((elm.FirstNode as XElement).Value);
                        (elm.FirstNode as XElement).Remove();
                        idList.Add(idAdd);
                    }

                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
                    {
                        XmlWriterSettings settings = new XmlWriterSettings();
                        settings.Indent = true;
                        using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                        {
                            if (type == "1")
                                writer.WriteStartElement("cctv");
                            else
                                writer.WriteStartElement("intsign");
                            writer.WriteStartElement("id");
                            writer.WriteString(id);
                            writer.WriteEndElement();
                            for (int i = 0; i < idList.Count; i++)
                            {
                                writer.WriteStartElement("id");
                                writer.WriteString(idList[i].ToString());
                                writer.WriteEndElement();
                            }
                            writer.WriteEndElement();
                            writer.WriteEndDocument();
                            writer.Flush();
                        }
                    }

                }
                catch (Exception)
                {
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, myIsolatedStorage))
                        {
                            XmlWriterSettings settings = new XmlWriterSettings();
                            settings.Indent = true;
                            using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
                            {
                                if (type == "1")
                                    writer.WriteStartElement("cctv");
                                else
                                    writer.WriteStartElement("intsign");
                                writer.WriteStartElement("id");
                                writer.WriteString(id);
                                writer.WriteEndElement();
                                writer.WriteEndElement();
                                // Ends the document
                                writer.WriteEndDocument();
                                // Write the XML to the file.
                                writer.Flush();
                            }
                        }
                    }
                }


                //XDocument xmlDoc = new XDocument(new XElement("student_ac",
                //new XElement("std_major", "5")));
                //xmlDoc.Save(fileStream);
                //fileStream.Close();
            }
            else
            {
                NavigationService.GoBack();
            }
        }

        private void refreshBtn_Click(object sender, System.EventArgs e)
        {
        	// TODO: Add event handler implementation here.
            
            waitScr.Visibility = Visibility.Visible;
            if (type == "1")
            {
                typetitletxt.Text = "CCTV";
                titletxt.Text = title;
                getImageFromCctv();
            }
            else
            {
                typetitletxt.Text = "INTELLIGENT TRAFFIC SIGNS";
                titletxt.Text = title;
                getImageFromVms();
            }
        }
    }
}
